<template>
  <div>
    <el-card>
      <!-- class="project-list-container" -->
      <div>
        <div class="list-h">
          <div class="add-option">
            <el-button v-auth="`/expert/device-add`" type="primary" @click="add"
              >添加</el-button
            >
            <!-- <el-button v-auth="`/expert/device-import`" type="primary"
              >导入</el-button
            > -->
          </div>
          <el-form
            :inline="true"
            class="demo-form-inline"
            :model="formInline"
            ref="formRef"
            @submit.prevent
          >
            <el-form-item label="设备名称" prop="deviceNameLike">
              <el-input
                v-model.trim="formInline.deviceNameLike"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>
            <el-form-item label="设备品牌" prop="deviceBrandLike">
              <el-input
                v-model.trim="formInline.deviceBrandLike"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>
            <el-form-item label="设备型号" prop="deviceModelLike">
              <el-input
                v-model.trim="formInline.deviceModelLike"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>
            <el-form-item label="所属部门" prop="deptNameLike">
              <el-input
                v-model.trim="formInline.deptNameLike"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>

            <el-form-item>
              <el-button @click="handleReset">重置</el-button>
              <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-skeleton :rows="8" :loading="loading" animated>
          <div class="device-box">
            <el-card
              class="device-card"
              shadow="hover"
              v-for="(item, index) in tableData"
              :key="index"
            >
              <div class="header">
                <div class="title">{{ item.deviceName }}</div>
                <div class="btns">
                  <el-button
                    @click="edit(item)"
                    v-auth="`/expert/device-edit`"
                    type="text"
                    icon="el-icon-edit"
                  ></el-button>

                  <el-popconfirm
                    confirm-button-text="确定"
                    cancel-button-text="取消"
                    icon="el-icon-info"
                    icon-color="red"
                    title="确定删除该设备吗？"
                    @confirm="handleDelete(item)"
                  >
                    <template #reference>
                      <el-button
                        v-auth="`/expert/device-del`"
                        type="text"
                        icon="el-icon-delete"
                      ></el-button> </template
                  ></el-popconfirm>
                </div>
              </div>
              <div class="tag-box">
                <el-tag type="success"
                  >可用 | {{ item.deviceNumAvailable }}</el-tag
                >
                <el-tag type="warning"
                  >维修 | {{ item.deviceNumMaintain }}</el-tag
                >
                <el-tag type="info">下架 | {{ item.deviceNumOff }}</el-tag>
              </div>
              <div class="info-box">
                <div class="info">
                  <p>品牌：{{ item.deviceBrand }}</p>
                  <p>型号：{{ item.deviceModel }}</p>
                  <p>所属单位：{{ item.deptName }}</p>
                  <p>购置时间：{{ item.acquisitionDate.split(" ")[0] }}</p>
                </div>
                <div class="info-img">
                  <img :src="item.src" alt="" />
                </div>
              </div>
              <div class="footer">
                <p>
                  <i class="el-icon-s-custom"></i>{{ item.custodianName }}
                  {{ item.custodianPhoneNum }}
                </p>
                <p>
                  <i class="el-icon-location-information"></i
                  >{{ item.deviceLocation }}
                </p>
              </div>
            </el-card>
          </div>
        </el-skeleton>
      </div>
      <re-pagination
        :total="total"
        v-show="total > 0"
        v-model:page="formInline.pageNum"
        v-model:limit="formInline.pageSize"
        @pagination="handleSearch"
      />
    </el-card>
  </div>
  <el-dialog
    :title="mode === 'add' ? '添加设备' : '编辑设备'"
    v-model="dialogFormVisible"
    destroy-on-close
    width="600px"
  >
    <el-form
      :model="formData"
      ref="dformRef"
      @submit.prevent
      :rules="formRules"
      label-width="100px"
      :validate-on-rule-change="false"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="formData.deviceName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备品牌" prop="deviceBrand">
            <el-input v-model="formData.deviceBrand"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备型号" prop="deviceModel">
            <el-input v-model="formData.deviceModel"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属单位" prop="deptCode">
            <el-cascader
              ref="cascader"
              style="width: 100%"
              popper-class="dept-cas"
              v-model="formData.deptCode"
              clearable
              filterable
              :options="joinDeptList"
              :props="defaultProps"
              placeholder="输入名称搜索"
              @change="handleDeptChange"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="保管人" prop="custodianUserId">
            <el-select
              v-model="formData.userObj"
              style="width: 100%"
              filterable
              clearable
              remote
              placeholder="请输入姓名搜索"
              :remote-method="querySearchAsync"
              value-key="id"
              @change="handleSelect"
            >
              <el-option
                id="default-option"
                v-for="item in userList"
                :key="item.id"
                :label="item.name"
                :value="item"
              ></el-option>
            </el-select>
            <!-- <el-input v-model="formData.dname"></el-input> -->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系方式" prop="custodianPhoneNum">
            <el-input v-model="formData.custodianPhoneNum"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备地点" prop="deviceLocation">
            <el-input v-model="formData.deviceLocation"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="购置日期" prop="acquisitionDate">
            <el-date-picker
              style="width: 100%"
              v-model="formData.acquisitionDate"
              value-format="YYYY-MM-DD hh:mm:ss"
              type="date"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备状态数量" prop="deviceNumAvailable">
            <el-input type="number" v-model="formData.deviceNumAvailable">
              <template #prepend>可用</template>
            </el-input>
            <el-input type="number" v-model="formData.deviceNumMaintain">
              <template #prepend>维修</template>
            </el-input>
            <el-input type="number" v-model="formData.deviceNumOff">
              <template #prepend>下架</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备图片" prop="devicePicture">
            <ecm-img-upload
              :files="files"
              :docid="docid"
              @setFile="setFile"
              :imgSrc="imgSrc"
            ></ecm-img-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row justify="end">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button @click="handleSubmit" type="primary">确 定</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script lang="ts">
import { reactive, toRefs, ref, defineComponent } from "vue";
import {
  getEquipmentList,
  addEquipment,
  updateEquipment,
  delEquipment
} from "/@/api/expert";
import { cloneDeep } from "lodash-es";
import { useRouter } from "vue-router";
import NotifMessage from "/@/utils/message/notification";
import { postDeptList } from "/@/api/dept";
import { postSysCompanyList } from "/@/api/organization";
import { getUsersForScience } from "/@/api/user";
import EcmImgUpload from "/@/components/ecmImage/index.vue";
import { getFileBolb, setAccToken } from "/@/utils/ecm";
export default defineComponent({
  name: "UserManage",
  components: {
    EcmImgUpload
  },
  setup() {
    const router = useRouter();
    const formRef = ref<HTMLFormElement | null>(null) as any;
    const dformRef = ref<HTMLFormElement | null>(null) as any;
    const cascader = ref<HTMLFormElement | null>(null) as any;
    let total = ref<number>(0);
    let joinDeptList = ref([]);
    let formInline = reactive({
      deptNameLike: "",
      deviceNameLike: "",
      deviceBrandLike: "",
      deviceModelLike: "",
      projectTypeCode: "",
      pageSize: 10,
      pageNum: 1,
      stageStatusUpper: "1"
    });

    let state = reactive({
      imgSrc: "",
      docid: window["ecmDocType"].common,
      files: [],
      userList: [],
      defaultProps: {
        children: "children",
        label: "deptDescShrt",
        value: "id",
        checkStrictly: true,
        emitPath: false
      },
      loading: true,
      formRules: {
        deviceName: [
          { required: true, message: "请输入设备名称", trigger: "blur" }
        ],
        deviceBrand: [
          { required: true, message: "请输入设备品牌", trigger: "blur" }
        ],
        deviceModel: [
          { required: true, message: "请输入设备型号", trigger: "blur" }
        ],
        deptCode: [
          { required: true, message: "请选择所属单位", trigger: "change" }
        ],
        custodianUserId: [
          { required: true, message: "请选择保管人", trigger: "change" }
        ],
        custodianPhoneNum: [
          { required: true, message: "请输入联系方式", trigger: "change" }
        ],
        deviceNumAvailable: [
          { required: true, message: "请输入设备状态数量", trigger: "change" }
        ],
        deviceNumMaintain: [
          { required: true, message: "请输入设备状态数量", trigger: "change" }
        ],
        deviceNumOff: [
          { required: true, message: "请输入设备状态数量", trigger: "change" }
        ],
        deviceLocation: [
          { required: true, message: "请输入设备地点", trigger: "change" }
        ],
        devicePicture: [
          { required: true, message: "请上传设备图片", trigger: "change" }
        ],
        acquisitionDate: [
          { required: true, message: "请选择购置日期", trigger: "change" }
        ]
      },
      target: null,
      formData: {
        userObj: null,
        custodianUserId: "",
        custodianName: "",
        deptCode: "",
        deptName: "",
        deviceName: "",
        deviceBrand: "",
        deviceModel: "",
        deviceLocation: "",
        acquisitionDate: "",
        custodianPhoneNum: "",
        deviceNumAvailable: "",
        deviceNumMaintain: "",
        deviceNumOff: "",
        devicePicture: null
      },
      dialogFormVisible: false,
      mode: "add",
      tableData: []
    });

    const edit = item => {
      state.mode = "edit";
      state.dialogFormVisible = true;
      state.formData = cloneDeep(item);
      state.formData.userObj = {
        id: item.custodianUserId,
        name: item.custodianName
      };
      state.imgSrc = item.src;
      // state.formData.devicePicture=
    };

    const handleDelete = async item => {
      const { code } = await delEquipment({
        id: item.id
      });
      if (code === 200) {
        handleSearch();
      }
    };
    const querySearchAsync = async (queryString = "") => {
      try {
        const params = {
          pageNum: 1,
          pageSize: 200,
          name: queryString
        };
        const { code, data } = await getUsersForScience(params);
        console.log(data, "datas");
        if (code === 200) {
          state.userList = data.list.map(item => {
            return {
              id: item.id,
              name: item.name,
              deptCode: item.deptCode,
              phoneNum: item.phoneNum,
              email: item.email,
              companyName: item.deptName
            };
          });
        }
      } catch (err) {
        console.log(err);
      }
    };

    const add = () => {
      state.formData = {
        userObj: null,
        custodianUserId: "",
        custodianName: "",
        deptCode: "",
        deptName: "",
        deviceName: "",
        deviceBrand: "",
        deviceModel: "",
        deviceLocation: "",
        acquisitionDate: "",
        custodianPhoneNum: "",
        deviceNumAvailable: "",
        deviceNumMaintain: "",
        deviceNumOff: "",
        devicePicture: null
      };
      state.imgSrc = "";
      state.dialogFormVisible = true;
      dformRef.value.resetFields();
    };

    const handleSelect = item => {
      state.formData.custodianUserId = item.id;
      state.formData.custodianName = item.name;

      formRef.value.clearValidate();
    };

    // 请求公司列表表格数据
    async function getTableData(obj: object = {}) {
      // 真实请求待添加
      state.loading = true;
      try {
        const { code, data } = await getEquipmentList(obj);
        if (code === 200) {
          state.loading = false;
          for (let i = 0; i < data.list.length; i++) {
            await getImage(data.list[i]);
          }

          state.tableData = data.list;
          total.value = data.rows;
        }
      } catch (err) {
        console.log(err);
      } finally {
        state.loading = false;
      }
    }

    const initDeptList = async () => {
      const { code, data } = await postDeptList({
        pageSize: 0
      });
      let deptList = [];
      if (code === 200) {
        deptList = data.map(item => {
          return {
            id: item.id,
            deptDescShrt: item.deptDescShrt,
            companyLegalName: item.companyLegalName,
            children: item.children
          };
        });
      }
      let companyList = [];
      const res = await postSysCompanyList({
        pageSize: 0
      });
      if (res.code === 200) {
        res.data.list.map(el => {
          companyList.push({
            id: el.id,
            companyLegalName: el.companyLegalName,
            deptDescShrt: el.companyName,
            isEmp: true
          });
        });
      }

      joinDeptList.value = [
        {
          deptDescShrt: "内部单位",
          disabled: true,
          children: deptList,
          id: "0-0"
        },
        {
          deptDescShrt: "外部单位",
          disabled: true,
          children: companyList,
          id: "0-1"
        }
      ];
    };

    const handleDeptChange = () => {
      const selected = cascader.value.getCheckedNodes();
      if (selected.length > 0) {
        state.formData.deptCode = selected[0].data.id;
        state.formData.deptName = selected[0].data.deptDescShrt;
      }
    };

    const handleSubmit = async () => {
      const isValid = await new Promise(resolve =>
        dformRef.value.validate(resolve)
      );
      if (isValid) {
        const params = cloneDeep(state.formData);
        if (state.mode === "add") {
          const { code, message } = await addEquipment(params);
          state.dialogFormVisible = false;
          if (code === 200) {
            NotifMessage.success("添加成功");
            handleSearch();
          } else {
            NotifMessage.error(message);
          }
        } else {
          const { code, message } = await updateEquipment(params);
          state.dialogFormVisible = false;
          if (code === 200) {
            NotifMessage.success("修改成功");
            handleSearch();
          } else {
            NotifMessage.error(message);
          }
        }
      }
    };
    const getImage = async item => {
      const json = JSON.parse(item.devicePicture);
      const bolb = await getFileBolb(json[0].uuidFile, json[0].url);

      const downloadURL = window.URL.createObjectURL(bolb);
      item["src"] = downloadURL;
    };

    // 清除表单，重置
    const handleReset = () => {
      formRef.value.resetFields();
      handleSearch();
    };

    // 根据条件进行搜索
    const handleSearch = (): void => {
      getTableData(formInline);
    };

    // 项目详情
    const handleEdit = (row, type): void => {
      router.push({
        path: "/project/feasibility/detail",
        query: { id: row.id, projectId: row.projectManageId, mode: type }
      });
    };
    const approval = (row): void => {
      console.log(row);
    };

    const setFile = file => {
      state.formData.devicePicture = JSON.stringify(file.file);
    };

    // 请求数据
    setAccToken();
    getTableData(formInline);
    initDeptList();
    querySearchAsync();
    return {
      add,
      handleDelete,
      edit,
      setFile,
      getImage,
      handleSubmit,
      cascader,
      joinDeptList,
      formInline,
      formRef,
      dformRef,
      total,
      ...toRefs(state),
      handleReset,
      handleSearch,
      handleEdit,
      approval,
      handleDeptChange,
      querySearchAsync,
      handleSelect
    };
  }
});
</script>
<style scoped lang="scss">
//device-box grid布局，每4个一行device-card
.device-box {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 20px;

  .device-card {
    ::v-deep .el-card__body {
      padding: 10px;
    }

    .header {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .tag-box {
      margin: 4px 0;
      display: flex;
      gap: 20px;
    }

    .info-box {
      display: flex;
      justify-content: space-between;

      p {
        margin-top: 4px;
        font-size: 14px;
        color: #939393;
      }

      .info-img {
        width: 80px;
        height: 80px;

        img {
          width: 100%;
          height: 100%;
        }
      }
    }

    .footer {
      margin-top: 10px;

      p {
        margin-bottom: 4px;
        font-size: 14px;

        i {
          margin-right: 4px;
          color: #f18408;
        }
      }
    }
  }
}
</style>
